package rs232Test;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;

import java.awt.Color;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.Map.Entry;

import javax.swing.JOptionPane;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.util.HexNumberFormat;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.experimental.chart.swt.ChartComposite;
import org.jfree.ui.RectangleInsets;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;

public class Control {

	protected Shell shell;
	/**
	 * 输出流
	 */
	static OutputStream out = null;
	SerialPort serialPort = null;
	private Combo combo;    //combo下拉框
	private Combo combo_1;
	private Combo combo_2;
	private Combo combo_3;
	private Combo combo_3_1;
	private Button btnNewButton;
	/**
	 * 心跳线程
	 */
	private Thread heartThread;//线程
	private Text text;         //文本类型
	private Label lblNewLabel_2;//标签类型
	private static Display display; //块类型
	private Button btnNewButton_2; //button类型
	/**
	 * 串口输入流线程
	 */
	private Thread isThread;
	/**
	 * 串口输入流
	 */
	private InputStream is;
	private Label lblNewLabel_3;
	private Text text_1;
	//十个快递柜勾选框
	private Button btnCheckButton_1;
	private Button btnCheckButton_2;
	private Button btnCheckButton_3;
	private Button btnCheckButton_4;
	private Button btnCheckButton_5;
	private Button btnCheckButton_6;
	private Button btnCheckButton_7;
	private Button btnCheckButton_8;
	private Button btnCheckButton_9;
	private Button btnCheckButton_10;
	
	
	private static MyMap dataMp=new MyMap();
    private static MyMap dataMp1=new MyMap();
    private static  TimeSeries s1 = new TimeSeries("当前温度", Second.class);
    private static  TimeSeries s2 = new TimeSeries("设定温度", Second.class);
    private static  TimeSeriesCollection dataset = new TimeSeriesCollection();
	private TimeSeriesCollection dataset2;
	
	
	/**
	 * 图表线程
	 */
	private Thread chartThred;
	
	
	/**
	 * 查询帧(10Byte)
	 */
	byte[] queryFrame = new byte[]{(byte)0xFF, (byte)0xFF, 0x0A, 0x00, 0x00, 0x01, 0x00, 0x00,(byte)0xFF,(byte)0xF7};
	private Label lblNewLabel_4;
	private static Text text_2;
	
	
	/**
	 * 状态数据
	 */
	static byte[] dataStatus=null;
	public static Button btnNewButton_3;
	private Button btnNewButton_4;
	private Text text_3;
	private Label lblNewLabel_5;
	
	/**
	 * 抽屉开关子窗口
	 */
	public static DrawerChoseDialog dcd;
	private Button btnCheckButton;
	private Spinner spinner;
	private Button btnNewButton_5;
	
	/**
	 * 输入流线程是否停止
	 */
	private boolean isThreadIfStop=false;
	private Button btnNewButton_6;
	
	static byte frameNumber=0;
	
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Control window = new Control();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
	
	/**
	 * 清理线程等工作
	 */
	private void close() {
		try {
			if(heartThread!=null) {
				if(heartThread.isAlive()) {
					heartThread.interrupt();	
					heartThread=null;
				}
			}
			if(isThread!=null) {
				if(isThreadIfStop=true) {
					isThread=null;
				}
			}
			
			if(chartThred!=null) {
				if(chartThred.isAlive()) {
					chartThred.interrupt();	
					chartThred=null;
				}
			}
			
			if(out!=null) {
				out.close();
				out=null;
			}
			if(serialPort!=null) {
				serialPort.close();
				serialPort=null;
			}
			if(is!=null) {
				is.close();
				is=null;
			}
			btnNewButton.setEnabled(true);
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		//窗口的设计：大小、标题、内容
		shell = new Shell();
		
		shell.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				close();
			}
		});
		//窗口大小
		shell.setSize(852, 730);
		//窗口标题
		shell.setText("采集与控制端");
		
		//连接按钮
		btnNewButton = new Button(shell, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				connect(); //匿名内部类实现连接
			}
		});		
		btnNewButton.setBounds(10, 10, 80, 27);
		btnNewButton.setText("连接");
		
		//断开按钮
		Button btnNewButton_1 = new Button(shell, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				close(); //匿名内部类实现断开
			}
		});

		btnNewButton_1.setText("断开");
		btnNewButton_1.setBounds(96, 10, 80, 27);
		
		//？？？？
		text = new Text(shell, SWT.BORDER |  SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
		text.setBounds(10, 92, 252, 148);
		//串口参数
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBounds(10, 456, 73, 29);
		lblNewLabel.setText("串   口：");
		//波特率参数
		Label lblNewLabel_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1.setText("波特率：");
		lblNewLabel_1.setBounds(10, 491, 73, 27);
		//校验位参数
		Label lblNewLabel_1_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1_1.setText("校验位：");
		lblNewLabel_1_1.setBounds(10, 531, 73, 27);
		//数据位参数
		Label lblNewLabel_1_1_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1_1_1.setText("数据位：");
		lblNewLabel_1_1_1.setBounds(10, 569, 80, 27);
		//停止位参数
		Label lblNewLabel_1_1_1_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1_1_1_1.setText("停止位：");
		lblNewLabel_1_1_1_1.setBounds(10, 611, 80, 29);
		//串口下拉框
		combo = new Combo(shell, SWT.NONE);
		combo.setItems(new String[] {"COM1", "COM2", "COM3", "COM4"});
		combo.setToolTipText("");
		combo.setBounds(109, 453, 88, 25);
		combo.setText("COM2");
		//波特率下拉框
		combo_1 = new Combo(shell, SWT.NONE);
		combo_1.setItems(new String[] {"300", "600", "1200", "2400", "4800", "9600", "19200", "38400", "43000", "56000", "57600", "115200"});
		combo_1.setBounds(109, 488, 88, 25);
		combo_1.setText("38400");
		//校验位下拉框
		combo_2 = new Combo(shell, SWT.NONE);
		combo_2.setItems(new String[] {"NONE", "ODD", "EVEN"});
		combo_2.setBounds(109, 528, 88, 25);
		combo_2.setText("NONE");
		//数据位下拉框
		combo_3 = new Combo(shell, SWT.NONE);
		combo_3.setItems(new String[] {"6", "7", "8"});
		combo_3.setBounds(109, 566, 88, 25);
		combo_3.setText("8");
		//停止位下拉框
		combo_3_1 = new Combo(shell, SWT.NONE);
		combo_3_1.setItems(new String[] {"1", "2"});
		combo_3_1.setBounds(109, 608, 88, 25);
		combo_3_1.setText("1");
		//接受数据框
		lblNewLabel_2 = new Label(shell, SWT.NONE);
		lblNewLabel_2.setText("接收的数据：");
		lblNewLabel_2.setBounds(10, 43, 109, 27);
		
		btnNewButton_2 = new Button(shell, SWT.NONE);
		btnNewButton_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				text.setText("");
				text_2.setText("");
			}
		});
		//清空按钮
		btnNewButton_2.setText("清空");
		btnNewButton_2.setBounds(182, 10, 80, 27);
		
		//当前温度框
		lblNewLabel_3 = new Label(shell, SWT.NONE);
		lblNewLabel_3.setText("当前温度：");
		lblNewLabel_3.setBounds(268, 13, 88, 27);
		
		//
		text_1 = new Text(shell, SWT.BORDER);
		text_1.setEnabled(false);
		text_1.setBounds(362, 8, 73, 23);
		
		//是个抽屉按钮
		btnCheckButton = new Button(shell, SWT.CHECK);
		btnCheckButton.setEnabled(false);
		btnCheckButton.setBounds(321, 62, 88, 27);
		btnCheckButton.setText("抽屉1");
		
		btnCheckButton_1 = new Button(shell, SWT.CHECK);
		btnCheckButton_1.setEnabled(false);
		btnCheckButton_1.setText("抽屉2");
		btnCheckButton_1.setBounds(421, 64, 81, 22);
		
		btnCheckButton_2 = new Button(shell, SWT.CHECK);
		btnCheckButton_2.setEnabled(false);
		btnCheckButton_2.setText("抽屉3");
		btnCheckButton_2.setBounds(508, 62, 74, 27);
		
		btnCheckButton_3 = new Button(shell, SWT.CHECK);
		btnCheckButton_3.setEnabled(false);
		btnCheckButton_3.setText("抽屉4");
		btnCheckButton_3.setBounds(588, 62, 99, 27);
		
		btnCheckButton_4 = new Button(shell, SWT.CHECK);
		btnCheckButton_4.setEnabled(false);
		btnCheckButton_4.setText("抽屉5");
		btnCheckButton_4.setBounds(693, 62, 88, 27);
		
		btnCheckButton_5 = new Button(shell, SWT.CHECK);
		btnCheckButton_5.setEnabled(false);
		btnCheckButton_5.setText("抽屉6");
		btnCheckButton_5.setBounds(321, 110, 80, 27);
		
		btnCheckButton_6 = new Button(shell, SWT.CHECK);
		btnCheckButton_6.setEnabled(false);
		btnCheckButton_6.setText("抽屉7");
		btnCheckButton_6.setBounds(422, 110, 80, 26);
		
		btnCheckButton_7 = new Button(shell, SWT.CHECK);
		btnCheckButton_7.setEnabled(false);
		btnCheckButton_7.setText("抽屉8");
		btnCheckButton_7.setBounds(508, 113, 88, 21);
		
		btnCheckButton_8 = new Button(shell, SWT.CHECK);
		btnCheckButton_8.setEnabled(false);
		btnCheckButton_8.setText("抽屉9");
		btnCheckButton_8.setBounds(588, 110, 88, 26);
		
		btnCheckButton_9 = new Button(shell, SWT.CHECK);
		btnCheckButton_9.setEnabled(false);
		btnCheckButton_9.setText("抽屉10");
		btnCheckButton_9.setBounds(692, 110, 88, 27);
		//压缩机按钮
		btnCheckButton_10 = new Button(shell, SWT.CHECK);
		btnCheckButton_10.setEnabled(false);
		btnCheckButton_10.setText("压缩机");
		btnCheckButton_10.setBounds(657, 12, 88, 22);
		
		JFreeChart chart = createChart(dataset);
        ChartComposite frame = new ChartComposite(shell, SWT.NONE,chart);
        frame.setBounds(268, 150, 494, 201);
        frame.setDisplayToolTips(true);  
        frame.setHorizontalAxisTrace(false);
        frame.setVerticalAxisTrace(false);
        
        //发送数据框
        lblNewLabel_4 = new Label(shell, SWT.NONE);
        lblNewLabel_4.setText("发送的数据：");
        lblNewLabel_4.setBounds(10, 246, 109, 29);
        
        text_2 = new Text(shell, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
        text_2.setBounds(10, 281, 252, 148);
        
        btnNewButton_3 = new Button(shell, SWT.NONE);
        btnNewButton_3.addSelectionListener(new SelectionAdapter() {

        	
        	
			@Override
        	public void widgetSelected(SelectionEvent e) {
				
				//shell.setEnabled(false);
				
				String drawerCode="";
				if(btnCheckButton.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_1.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_1.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_2.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_2.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_3.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_3.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_4.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_4.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_5.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_5.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_6.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_6.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_7.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_7.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_8.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_8.getSelection()) {
					drawerCode+="0";
				}
				
				if(btnCheckButton_9.getSelection()) {
					drawerCode+="1";
				}
				if(!btnCheckButton_9.getSelection()) {
					drawerCode+="0";
				}
				btnNewButton_3.setEnabled(false);
        		dcd = new DrawerChoseDialog(shell, 0,drawerCode);
        		dcd.open();
        		
        		
        		
        	}
        });
        btnNewButton_3.setText("开关指定抽屉");
        btnNewButton_3.setBounds(268, 383, 120, 27);
        
        btnNewButton_4 = new Button(shell, SWT.NONE);
        btnNewButton_4.addSelectionListener(new SelectionAdapter() {
        	@Override
        	public void widgetSelected(SelectionEvent e) {
        		onOrOffCompressor();
        	}
        });
        btnNewButton_4.setText("启/停温度控制");
        btnNewButton_4.setBounds(400, 383, 130, 27);
        
        text_3 = new Text(shell, SWT.BORDER);
        text_3.setEnabled(false);
        text_3.setBounds(558, 8, 73, 23);
        
        lblNewLabel_5 = new Label(shell, SWT.NONE);
        lblNewLabel_5.setText("设定的温度：");
        lblNewLabel_5.setBounds(441, 11, 117, 27);

        
        connect();
        btnNewButton.setEnabled(false);
        
        spinner = new Spinner(shell, SWT.BORDER);
        spinner.setMaximum(63);
        spinner.setMinimum(-63);
        spinner.setBounds(268, 435, 88, 27);
        
        btnNewButton_5 = new Button(shell, SWT.NONE);
        btnNewButton_5.addSelectionListener(new SelectionAdapter() {
        	@Override
        	public void widgetSelected(SelectionEvent e) {
        		byte[] setTemperature= {(byte)0xFF, (byte)0xFF ,(byte)0x0B ,(byte)0x78 ,(byte)0x01 ,(byte)0x04 ,(byte)0x10 ,(byte)0x8C ,(byte)0xC2 ,(byte)0xFF ,(byte)0xF7};
        		String tStr=spinner.getText();
        		int tInt=Integer.parseInt(tStr);
        		byte tByte=Byte.parseByte(String.valueOf(Math.abs(tInt)));
        		tByte=(byte)(tByte<<1);
        		if(tInt<0) {
        			tByte=(byte)(tByte|0x80);//7th：0-非负数，1-负数
        		}
        		setTemperature[6]=tByte;
        		outData(setTemperature);
        	}
        });
        btnNewButton_5.setText("设置控制温度");
        btnNewButton_5.setBounds(400, 435, 153, 27);
        
        btnNewButton_6 = new Button(shell, SWT.NONE);
        btnNewButton_6.addSelectionListener(new SelectionAdapter() {
        	@Override
        	public void widgetSelected(SelectionEvent e) {
        		SetParameterDialog spd = new SetParameterDialog(shell, 0);
        		spd.open();
        	}
        });
        btnNewButton_6.setText("设置参数");
        btnNewButton_6.setBounds(536, 383, 130, 27);
	}
	
	  private static XYDataset addToDataset(double temperatureCur,double temperatureSet) {//更新数据
	        Random r=new Random();//随机数
	        
	        System.out.println(temperatureCur);
	        System.out.println(temperatureSet);

	        dataMp.put(new Second(),temperatureCur);
	        dataMp1.put(new Second(), temperatureSet);
	        //cpuList.add(cpuuse);
	        s1.clear();
	        s2.clear();
	        for(Entry<Second,Double> e:dataMp.entrySet() ){
	            s1.add(e.getKey(),e.getValue());
	        }
	        for(Entry<Second,Double> e:dataMp1.entrySet() ){
	            s2.add(e.getKey(),e.getValue());
	        }
	        
	        dataset.removeAllSeries();
	        dataset.addSeries(s1);
	        dataset.addSeries(s2);

	        return dataset;
	    }
	
	private static JFreeChart createChart(XYDataset dataset) {

        JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "当前温度/设定温度曲线图",  // title
            "时间",             // x-axis label
            "温度",   // y-axis label
            dataset,            // data
            true,               // create legend?
            true,               // generate tooltips?
            false               // generate URLs?
        );

        chart.setBackgroundPaint(Color.white);


        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);
        plot.getRangeAxis().setUpperBound(63);
        plot.getRangeAxis().setLowerBound(-63);
        XYItemRenderer r = plot.getRenderer();
        if (r instanceof XYLineAndShapeRenderer) {
            XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
            renderer.setBaseShapesVisible(true);
            renderer.setBaseShapesFilled(true);
        }

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));

        return chart;

    }
	
	/**
	 * 输出数据
	 * @param data
	 */
	public static void outData(byte[] data) {
		frameNumber++;
		String s=Util.bytesToHexString(data);
		s=s.substring(4, s.length());//去除信息头
		s=s.substring(0, s.length()-8);//去除校验位和结束标志
		
		StringBuilder sb=new StringBuilder(s);
		s=sb.replace(2, 4, String.format("%02x", new Integer(frameNumber & 0xff)).toUpperCase()).toString();
		
		byte[] b=Util.hexToByteArray(s);
		String crc=Util.getCRC(b);//算出CRC的值
		s="FFFF"+s+crc+"FFF7";//加上信息头 CRC 和结束标志
		data=Util.hexToByteArray(s);
		
		final byte[] data_=data;
		
		display.asyncExec(new Runnable() {
			@Override
			public void run() {
				try {
					if(text_2.getText().length()>10240) {
						text_2.setText("");
					}
					text_2.setText(text_2.getText()+Util.bytesToHexString(data_)+"\n");
					out.write(data_);
					out.flush();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * 刷新状态
	 * 	FF FF 2C 00 00 10 
	 * 10 01 00 00 01 01 05 01 1E 07 08 08 02 FF 03 FF 03 20 
	 * 10 01 00 00 01 00 00 00 08 3C FF FF 00 00 00 00 
	 * 1C EB FF F7
	 */
	public void refreshStatus() {
		
		//刷新抽屉状态
		byte drawerHigh=dataStatus[36];
		byte drawerLow=dataStatus[37];
		String sh=Util.byte2bits(drawerHigh);
		String sl=Util.byte2bits(drawerLow);
		
		if(sh.substring(7,8).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton.setSelection(false);
				}
			});
		}
		if(sh.substring(7,8).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton.setSelection(true);					
				}
			});
		}
		
		if(sh.substring(6,7).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_1.setSelection(false);					
				}
			});
		}
		if(sh.substring(6,7).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_1.setSelection(true);					
				}
			});
		}
		
		if(sh.substring(5,6).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_2.setSelection(false);					
				}
			});
		}
		if(sh.substring(5,6).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_2.setSelection(true);					
				}
			});
		}
		
		if(sh.substring(4,5).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_3.setSelection(false);					
				}
			});
		}
		if(sh.substring(4,5).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_3.setSelection(true);					
				}
			});
		}
		
		if(sh.substring(3,4).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_4.setSelection(false);					
				}
			});
		}
		if(sh.substring(3,4).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_4.setSelection(true);					
				}
			});
		}
		
		if(sh.substring(2,3).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_5.setSelection(false);					
				}
			});
		}
		if(sh.substring(2,3).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_5.setSelection(true);					
				}
			});
		}
		
		if(sh.substring(1,2).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_6.setSelection(false);					
				}
			});
		}
		if(sh.substring(1,2).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_6.setSelection(true);					
				}
			});
		}
		
		if(sh.substring(0,1).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_7.setSelection(false);					
				}
			});
		}
		if(sh.substring(0,1).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_7.setSelection(true);					
				}
			});
		}
		
		if(sl.substring(7,8).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_8.setSelection(false);					
				}
			});
		}
		if(sl.substring(7,8).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_8.setSelection(true);					
				}
			});
		}
		
		if(sl.substring(6,7).equals("0")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_9.setSelection(false);					
				}
			});
		}
		if(sl.substring(6,7).equals("1")) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_9.setSelection(true);					
				}
			});
		}
		
		//System.out.println(sh);
		//System.out.println(sl);
		
		//刷新压缩机状态 0-停止，1-预启动，2-运行，3-故障
		if(dataStatus[31]==0x0||dataStatus[31]==0x1) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_10.setSelection(false);
				}
			});
		}
		if(dataStatus[31]==0x2) {
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					btnCheckButton_10.setSelection(true);
				}
			});
		}
		
		//当前温度
		byte temperatureCurByte=dataStatus[33];
		display.asyncExec(new Runnable() {
			@Override
			public void run() {
				text_1.setText(getTemperature(temperatureCurByte));
			}
		});
		//设定的温度
		byte temperatureSetByte=dataStatus[32];
		display.asyncExec(new Runnable() {
			@Override
			public void run() {
				text_3.setText(getTemperature(temperatureSetByte));
			}
		});
		
		if(Double.parseDouble(getTemperature(temperatureCurByte))<Double.parseDouble(getTemperature(temperatureSetByte))) {
			onOrOffCompressor();
		}
		
		Display.getDefault().asyncExec(new Runnable() {
            public void run() {
            	addToDataset(Double.parseDouble(getTemperature(temperatureCurByte)),Double.parseDouble(getTemperature(temperatureSetByte)));
            }
        });
		
		
	}
	
	public String getTemperature(byte data) {
		String temperatureStr=Util.byte2bits(data);
		int ifPlus=Integer.parseInt(temperatureStr.substring(0,1));//7th：0-非负数，1-负数
		int temperatureInt=Util.bit2byte(temperatureStr.substring(1,7));//1th-6th：温度值整数部分（0-63）
		int decimal=Integer.parseInt(temperatureStr.substring(7,8));//0th：温度值小数部分 1-0.5，0-0
		String temperature="";
		if(ifPlus==1) {
			temperature+="-";
		}
		temperature+=String.valueOf(temperatureInt);
		if(decimal==0) {
			temperature+=".0";
		}
		if(decimal==1) {
			temperature+=".5";
		}
		return temperature;
	}
	
	
	
	
	
	public void connect() {
		try {
			 //通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(combo.getText());
            //打开端口，并给端口名字和一个timeout（打开操作的超时时间）
            CommPort commPort = portIdentifier.open(combo.getText(), 2000);
            //判断是不是串口
            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                //设置一下串口的波特率等参数 baudrate 
                //serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                int PARITY=SerialPort.PARITY_NONE;
                if(combo_2.getText().equals("NONE")) {
                	PARITY=SerialPort.PARITY_NONE;
                }
                if(combo_2.getText().equals("ODD")) {
                	PARITY=SerialPort.PARITY_ODD;
                }
                if(combo_2.getText().equals("EVEN")) {
                	PARITY=SerialPort.PARITY_EVEN;
                }
                serialPort.setSerialPortParams(Integer.parseInt(combo_1.getText()), Integer.parseInt(combo_3.getText()), Integer.parseInt(combo_3_1.getText()),PARITY);
                
            }
            out = serialPort.getOutputStream();
            is = serialPort.getInputStream();
            
            isThread = new Thread(new Runnable() {
				

				@Override
				public void run() {
					try {
						while(true) {
							if(isThreadIfStop) {
								break;
							}else {
								try {
									int availableBytes=is.available();
									byte[] cache = new byte[availableBytes];
									if (availableBytes > 0) {
										is.read(cache);
										String dataHex=Util.bytesToHexString(cache);
										if(dataHex.length()>4) {
											if(dataHex.substring(0, 4).equals("FFFF")) {//消息头
												if(dataHex.substring(dataHex.length()-4, dataHex.length()).equals("FFF7")) {//消息尾
													dataStatus=cache;
													display.asyncExec(new Runnable() {
														@Override
														public void run() {
															text.setText(text.getText()+dataHex+"\n");
														}
													});
													
													String functionNum=Util.bytesToHexString(Util.getBit(cache, 5,1));//功能号
													if(functionNum.equals("10")) {
														refreshStatus();
													}
													
												}
											}
										}
									}
								} catch (ArrayIndexOutOfBoundsException e) {
									continue;
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
            
            heartThread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while(true) {
							if(Thread.currentThread().isInterrupted()) {
								break;
							}else {
								
								//String time=String.valueOf(new Date().getTime());
								//System.out.println(time);
								
								/*
								display.asyncExec(new Runnable() {
									@Override
									public void run() {
										text.setText(text.getText()+time);
									}
								});
								*/
								System.out.println("heartThread查询帧线程");
								
								outData(queryFrame);
							}
							Thread.sleep(1000);
			            }	
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
            //heartThread.start();
            isThread.start();
            btnNewButton.setEnabled(false);
           
		} catch (Exception e) {
			MessageBox msg=new MessageBox(shell);
			msg.setText("提示");
			msg.setMessage("连接失败！");
			msg.open();
			e.printStackTrace();
		} 
		
		
		
		chartThred = new Thread(new Runnable() {
            public void run() {
            	 try {
            		 while (true) {
                    	if(Thread.currentThread().isInterrupted()) {
                    		break;
                    	}else {
                    		Thread.sleep(1000);
                            //System.out.println("aaaa");
                            Display.getDefault().asyncExec(new Runnable() {
                                public void run() {
                                    //addToDataset();
                                }
                            });
                    	}
                    }
                }
            	catch (InterruptedException e) {
            		e.printStackTrace();
            	}
            }
        });
		//chartThred.start();
		
		
		
		
	}
	
	/**
	 * 抽屉窗口回调
	 * 开关指定抽屉
	 * @param data 1111101111
	 */
	public static void openCloseDrawer(String data) {
		btnNewButton_3.setEnabled(true);
		
		String high=data.substring(0,8);
		high=new StringBuffer(high).reverse().toString();//反转字符串
		String low=data.substring(8,10);
		low=new StringBuffer(low).reverse().toString();//反转字符串
		
		//System.out.println(high);
		//System.out.println(low);
		
		byte highB=Util.bit2byte(high);
		byte lowB=Util.bit2byte(low);
		
		byte[] dataS= {(byte)0xFF,(byte)0xFF ,(byte)0x0C ,(byte)0x77 ,(byte)0x01 ,(byte)0x03 ,(byte)0xDE ,(byte)0x03 ,(byte)0x1E ,(byte)0x58 ,(byte)0xFF ,(byte)0xF7};
		//byte openHeight=0x01;
		//byte openLow=0x00;
		//System.out.println(statusData[35]);
		//System.out.println(statusData[36]);
		//dataS[6]=(byte) (statusData[36]&highB);
		//dataS[7]=(byte) (statusData[37]&lowB);
		dataS[6]=highB;
		dataS[7]=lowB;
		outData(dataS);
		dcd.shell.dispose();
	}
	
	/**
	 * 关闭或者打开压缩机
	 */
	private void onOrOffCompressor() {
		byte[] dataS= {(byte)0xFF, (byte)0xFF ,(byte)0x0B ,(byte)0x76 ,(byte)0x01 ,(byte)0x02 ,(byte)0x01 ,(byte)0x60 ,(byte)0xC8 ,(byte)0xFF ,(byte)0xF7};
		System.out.println(dataStatus[31]);
		if(dataStatus[31]==0x0) {
			dataS[6]=0x1;
		}
		if(dataStatus[31]==0x2) {
			dataS[6]=0x0;
		}
		outData(dataS);	
	}  
	
}
